<template>
  <div>
    <div id="container"/>
    <div class="execution-box">
      <!--v-if="haveLocationed"-->
      <div @click="uploadLocation" class="execution" >
        <div style="text-align: center;padding: 25px 0;">
          <span style="font-size: 1.2rem;font-weight: bold">{{time}}</span>
          <br/>
          <span>{{excutioned?"已打卡":"打卡"}}</span>
        </div>
      </div>
    </div>
    <loading :show="!finished" text="定位中"></loading>
    <div v-transfer-dom>
      <confirm v-model="showError"
               @on-cancel="showError = false"
               @on-confirm="punch">
        <div>
          <icon type="warn" is-msg></icon>
          <p style="color: red">您未到达打卡范围，距离 {{Math.ceil(distanceError)}} 米，是否继续打卡？</p></div>
      </confirm>
    </div>
  </div>
</template>

<script>
  import AMap from 'AMap'
  import {Loading, XCircle, Icon, Toast,Confirm ,TransferDomDirective as TransferDom } from 'vux'

  export default {
    components: {
      Loading,
      XCircle,
      Icon,
      Toast,
      Confirm,
    },
    directives: {
      TransferDom
    },
    data() {
      return {
        userInfo: null,
        finished: false,
        longitude: null,
        latitude: null,
        haveLocationed: false,
        excutioned: false,
        map: null,
        myMarker: null,
        pointCircle: null,
        attendPointMarker: null,
        time: '',
        showError: false,
        distanceError:'',
      };
    },
    mounted() {
      this.$getUserInfo().then(userInfo => {
        setTimeout(() => {
          if (this.finished == false) {
            this.warn("获取位置超时，请重试");
          }
        }, 15000);
        this.map = new AMap.Map('container', {
          resizeEnable: true,
          zoom: 15,
        });
        this.userInfo = userInfo
        this.$register(["getLocation", "closeWindow", 'chooseImage', 'uploadImage'])
          .then(() => {
            this.getLocation();
            this.getTime();
          }).catch((msg, error) => {
          //要么注册出错，要么什么出错。。
          this.warn(msg);
          console.log(error)
        });
      });
    },
    methods: {
      //获取时间
      getTime() {
        let hours = new Date().getHours()
        hours = hours > 9 ? hours : '0' + hours;
        let minutes = new Date().getMinutes()
        minutes = minutes > 9 ? minutes : '0' + minutes;
        this.time = hours + ':' + minutes
      },
      //获取位置
      getLocation() {
        this.$wechat.getLocation({
          type: "gcj02",
          success: res => {
            // alert("位置获取完成")
            if (res.errMsg === "getLocation:ok") {
              this.longitude = res.longitude
              this.latitude = res.latitude
              this.getLocationed();
              //10秒后再次获取位置
              setTimeout(() => {
                this.getLocation();
                this.getTime();
              }, 10000)
            } else {
              this.warn("未知原因导致获取地理位置失败");
            }
          },
          error: res => {
            this.warn("未知原因导致微信获取地理位置失败");
          },
          cancel: function (res) {
            this.warn("由于您拒绝程序获取位置，导致打卡失败。");
          }
        });
      },
      //获取到位置
      getLocationed() {
        this.finished = true
        this.haveLocationed = true
        //移动到自己的位置，并显示自己位置
        this.map.panTo([this.longitude, this.latitude]);
        if (this.myMarker) {
          this.map.remove(this.myMarker)
        }
        this.myMarker = new AMap.Marker({
          icon: require("@/assets/images/mark_b.png"),
          position: [this.longitude, this.latitude],
          animation: "AMAP_ANIMATION_DROP",
          zIndex: 1000,
          offset: new AMap.Pixel(-10, -31)
        });
        this.map.add(this.myMarker)

        //获取打卡点位置信息
        this.$http.get("/attendance/api/chief/nearest", {
          params: {
            wkt: "POINT(" + this.longitude + " " + this.latitude + ")",
            fields: "departments",
            include: false
          }
        }).then(res => {
          let data = res.data.data
          let wkt = data.wkt
          this.wktArr = wkt.match(/\((.*) (.*)\)/);
          this.distance = data.distance;
          if (this.attendPointMarker) {
            this.map.remove(this.attendPointMarker);
          }
          this.attendPointMarker = new AMap.Marker({
            icon: require("@/assets/images/department.png"),
            position: [this.wktArr[1], this.wktArr[2]],
            offset: new AMap.Pixel(-13, -16),
          });
          this.map.add(this.attendPointMarker)
          if (this.pointCircle) {
            this.map.remove(this.pointCircle);
          }
          //为了减少显示时候的误差
          // let distance = data.distance - 70
          this.pointCircle = new AMap.Circle({
            center: new AMap.LngLat(this.wktArr[1], this.wktArr[2]),// 圆心位置
            radius: this.distance, //半径
            strokeColor: "#4892ff", //线颜色
            strokeOpacity: 0.3, //线透明度
            strokeWeight: 3, //线粗细度
            fillColor: "#4892ff", //填充颜色
            fillOpacity: 0.25//填充透明度
          });
          this.map.add(this.pointCircle)
        })
      },
      warn(msg, des) {
        this.finished = true
        this.$vux.toast.show({
          type: "warn",
          text: msg
        })
        setTimeout(() => {
          this.$vux.loading.hide()
        }, 2000)
      },
      uploadLocation() {
        // 上传位置
        if (this.$is_weixin()) {
          if ((!this.excutioned) && this.longitude && this.wktArr) {
            let dis = AMap.GeometryUtil.distance([this.longitude, this.latitude], [this.wktArr[1], this.wktArr[2]]);
            if (dis > this.distance) {
              this.showError = true;
              this.distanceError = dis - this.distance;
              // this.$vux.confirm.show({
              //   content: '<div><icon type="warn" is-msg></icon><p style="color: red">您未到达打卡范围，距离 ' + Math.ceil(dis - this.distance) + ' 米，是否继续打卡？</p></div>',
              //   onCancel: () => {
              //
              //   },
              //   onConfirm: () => {
              //     this.punch();
              //   }
              // })
            } else {
              this.punch();
            }
          } else {
            this.$vux.toast.show({
              text: '获取位置信息失败',
              type: 'warn'
            });
          }
        } else {
          this.$vux.toast.show({
            text: '仅支持微信打卡',
            type: 'warn'
          });
        }
      },
      punch() {
        this.$wechat.chooseImage({
          sizeType: ['original'],
          sourceType: ['camera'],
          success: (res) => {
            if (res.errMsg == 'chooseImage:ok') {
              this.$wechat.uploadImage({
                localId: res.localIds[0],
                isShowProgressTips: 1,
                success: (resp) => {
                  if (resp.errMsg == 'uploadImage:ok') {
                    this.$http.post('/wechat/resource/prove', {
                      mediaId: resp.serverId
                    }).then(data => {
                      if (data.data.code == 200) {
                        this.$http.post("/attendance/api/punch", {
                          punchFileStore: data.data.data.id,
                          sysUser: {
                            id: this.userInfo.id
                          },
                          wkt: "POINT(" + this.longitude + " " + this.latitude + ")"
                        })
                          .then(res => {
                            this.finished = true;
                            this.$vux.toast.show({
                              type: "success",
                              text: "打卡成功"
                            });
                            setTimeout(() => {
                              this.$vux.loading.hide()
                            }, 2000)
                            this.excutioned = true;
                          })
                          .catch(res => {
                            this.warn(res.data.msg);
                          });
                      }
                    });
                  } else {
                    this.$vux.toast.show({
                      text: '上传图片失败',
                      type: 'warn'
                    });
                  }
                }
              });
            } else {
              this.$vux.toast.show({
                text: '选择图片失败',
                type: 'warn'
              });
            }
          },
        });
      },
    }
  };
</script>
<style>
  html, body {
    margin: 0;
    padding: 0;
  }

  #container {
    height: 100%;
    width: 100%;
    position: fixed;
  }

  .execution-box {
    pointer-events: none;
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
    position: fixed;
    display: flex;
    justify-content: center;
    align-items: flex-end
  }

  .execution {
    pointer-events: auto;
    width: 100px;
    height: 100px;
    margin-bottom: 20px;
    background-color: #ffffff;
    border-radius: 50%;
    border: 10px solid #43A2FE;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    opacity: 0.95;
    -webkit-box-shadow: #ccc 0px 10px 10px;
    -moz-box-shadow: #ccc 0px 10px 10px;
    box-shadow: #ccc 0px 10px 10px;
  }

  .execution > span {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: Center;
    text-align: center;
  }
</style>
